package com.smartlink.app.controller;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.smartlink.app.activity.BaseActivity;
import com.smartlink.app.activity.LoginActivity;
import com.smartlink.app.activity.MainActivity;
import com.smartlink.app.common.Constant;
import com.smartlink.app.pojo.Student;
import com.smartlink.app.pojo.Teacher;
import com.smartlink.app.util.JSONUtils;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 用于教师和学生的登陆控制器
 * Created by Administrator on 2016/7/7.
 */
public class LoginController {

    private static final String TAG = "LoginController";
    private Context ctx;
    private SharedPreferences sp;

    public LoginController(Context ctx) {
        this.ctx = ctx;
        this.sp = ctx.getSharedPreferences("main", Context.MODE_PRIVATE);
    }

    /**
     * 用户登录  区分用户类型通过shareperferce 的 uesrType  学生： userType=0   教师 ：userType=999
     *
     * @param number
     * @param password
     */
    public void login(String number, String password, final Handler handler) {
        //登录URL
        String ip = sp.getString("ip", Constant.HTTP.HTTP_PORT);
        final String path = "http://" + ip + ":8080/smartlink/login";
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        //post请求设置参数
        RequestParams rp = new RequestParams();
        rp.put("number", number);
        rp.put("password", password);
        asyncHttpClient.post(path, rp, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                //将服务器返回数据
                String body = new String(responseBody);
                //判断服务器是否返回为空
                if ("{\"teacher\":\"null\"}".equals(body) || "{\"student\":\"null\"}".equals(body)) {
                    if (handler == null) {
                        Intent intent = new Intent(ctx, LoginActivity.class);
                        intent.putExtra("error", "自动登陆失败，请重新登陆");
                        ctx.startActivity(intent);

                    } else {
                        Message message = handler.obtainMessage();
                        message.obj = "输入有误";
                        handler.sendMessage(message);
                    }

                } else {
                    //获取相应属性
                    Student student = null;
                    Teacher teacher = null;
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(body);
                        Gson gson = new Gson();
                        try {
                            JSONObject jsonStudent = (JSONObject) jsonObject.get("student");
                            //学生登录成功
                            student = gson.fromJson(jsonStudent.toString(), Student.class);
                            System.out.println("Student" + student);
                            saveStudentMessage(student);
                        } catch (Exception e) {
                            e.printStackTrace();
                            try {
                                //教师登录成功
                                JSONObject jsonTeacher = (JSONObject) jsonObject.get("teacher");
                                teacher = gson.fromJson(jsonTeacher.toString(), Teacher.class);
                                saveTeacherMessage(teacher);

                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (handler != null) {
                        Message message = handler.obtainMessage();
                        message.obj = "登陆成功";
                        message.what = 0x123;
                        handler.sendMessage(message);
                    }
                    //启动主界面
                    Intent intent = new Intent(ctx, MainActivity.class);
                    ctx.startActivity(intent);
                    //结束启动页
                }
            }

            //登录失败，一般为url出错
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (handler == null) {
                    Intent intent = new Intent(ctx, LoginActivity.class);
                    intent.putExtra("error", "网络错误，请重新登陆");
                    ctx.startActivity(intent);

                } else {
                    Message message = handler.obtainMessage();
                    message.obj = "登录失败，请检测网络";
                    handler.sendMessage(message);
                }
            }
        });
    }

    /**
     * 保存学生记录到 SharedPreferences
     *
     * @param student
     */
    private void saveStudentMessage(Student student) {
        Log.i(TAG, "saveStudentMessage: " + student);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("number", student.getStudentId());
        editor.putString("name", student.getName());
        editor.putString("password", student.getPasswrod());
        editor.putInt("userType", 0);
        editor.apply();
    }

    /**
     * 保存教师记录到 SharedPreferences
     *
     * @param teacher
     */
    private void saveTeacherMessage(Teacher teacher) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("number", teacher.getJobNumber());
        editor.putString("name", teacher.getName());
        editor.putString("password", teacher.getPassword());
        editor.putInt("userType", 999);
        editor.apply();
    }


}
